<template>
  <div>
    <article class="main-breadcrumb">
      <el-breadcrumb separator=">" class="main-breadcrumb-wrap">
        <el-breadcrumb-item>
          <span class="main-breadcrumb-home">排程管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span class="main-breadcrumb-home">排程工具</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </article>
    <div class="nx-content">
      <div class="flex-bet">
        <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="">
            <el-cascader v-if="userType == 0" v-model="searchForm.companyId" placeholder="请选择公司名称" :options="companyArray"
              :props="{
                checkStrictly: true,
                value: 'id',
                label: 'name',
                children: 'childList',
              }" style="width: 190px" @change="changeTreeItem" clearable></el-cascader>
          </el-form-item>
          <el-form-item label="">
            <el-select v-model="searchForm.baseId" placeholder="请选择基地名称" style="width: 190px !important" clearable>
              <el-option v-for="item in baseArray" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <div v-allow="'030102'" class="search-btn" @click="onSubmit"></div>
          </el-form-item>
          <!-- <el-form-item>
            <div v-allow="'030102'" class="reset-btn" @click="resetForm"></div>
          </el-form-item> -->
        </el-form>
        <!-- <div class="left-title flex">
          <div v-allow="'030101'" style="margin-top: -1rem !important" class="add-btn" @click="handleAdd()">
            添加模板
          </div>
        </div> -->

      </div>
      <div>

        <oxygenation></oxygenation>
      </div>
      <div>

        <pollution></pollution>
      </div>
      <div>

        <batchCharge></batchCharge>
      </div>
      <div>
        <div class="title">
          任务配置
        </div>
        <el-form :model="ruleForm" :rules="rules" ref="formName" label-width="120px" class="demo-ruleForm"
          :class="{ 'form-rules-show': seeType }">
          <el-row>
            <el-col :span="9" style="margin-left: 10rem;">

              <el-form-item label="首次任务开始时间：" label-width="150px" prop="time">
                <el-time-picker v-model="ruleForm.startTime" format="HH:mm" value-format="HH:mm" placeholder="首次任务开始时间">
                </el-time-picker>
              </el-form-item>


            </el-col>
            <el-col :span="6" style="margin-left: 2.5rem;">
              <el-form-item label="任务执行时间间隔：" label-width="200px">
                <el-input v-model="ruleForm.timeInterval" placeholder="请输入每次任务执行时间间隔" clearable show-word-limit
                  :disabled="seeType">
                  <i slot="suffix" class="dw">(分钟)</i>
                </el-input>
              </el-form-item>
            </el-col>


          </el-row>
          <el-row>
            <el-col :span="8" style="margin-left: 10rem;">
              <el-form-item label="增氧任务执行组数：" label-width="150px">
                <!-- <el-input-number v-model="ruleForm.zyTaskNum" @keydown.native="channelInputLimit"
                    @change="handleChange(0)" :min="0"></el-input-number> -->
                <div
                  style="font-size: 1.2rem; border: 1px solid #e6e8eb;border-radius: 10px;width:16rem; display: flex;justify-content: space-between;">
                  <i @click="down(3)"
                    style="cursor: pointer;text-align: center;;line-height: 3rem;background-color: #f5f7fa;width: 3.5rem;"
                    class="el-icon-minus"></i>
                  {{ ruleForm.zyTaskNum }}
                  <i @click="up(3)"
                    style="cursor: pointer;text-align: center;;line-height: 3rem;background-color: #f5f7fa;width: 3.5rem;"
                    class="el-icon-plus"></i>
                </div>
                <!-- <el-input v-model="ruleForm.zyTaskNum" placeholder="请输入增氧任务执行组数" clearable show-word-limit
                    :disabled="seeType"></el-input> -->
              </el-form-item>
            </el-col>
            <el-col :span="8" style="margin-left: 11.5rem;">
              <el-form-item label="排污任务执行组数：" label-width="150px">
                <!-- <el-input-number v-model="ruleForm.pwTaskNum" @keydown.native="channelInputLimit" @change="handleChange"
                    :min="0"></el-input-number> -->
                <div
                  style="font-size: 1.2rem; border: 1px solid #e6e8eb;border-radius: 10px;width:16rem; display: flex;justify-content: space-between;">
                  <i @click="down(2)"
                    style="cursor: pointer;text-align: center;;line-height: 3rem;background-color: #f5f7fa;width: 3.5rem;"
                    class="el-icon-minus"></i>
                  {{ ruleForm.pwTaskNum }}
                  <i @click="up(2)"
                    style="cursor: pointer;text-align: center;;line-height: 3rem;background-color: #f5f7fa;width: 3.5rem;"
                    class="el-icon-plus"></i>
                </div>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>

            <el-col :span="8" style="margin-left: 10rem;">
              <el-form-item label="换水任务执行组数：" label-width="150px">
                <!-- <el-input-number v-model="ruleForm.hsTaskNum" @keydown.native="channelInputLimit" @change="handleChange"
                    :min="0"></el-input-number> -->
                <div
                  style="font-size: 1.2rem; border: 1px solid #e6e8eb;border-radius: 10px;width:16rem; display: flex;justify-content: space-between;">
                  <i @click="down(1)"
                    style="cursor: pointer;text-align: center;;line-height: 3rem;background-color: #f5f7fa;width: 3.5rem;"
                    class="el-icon-minus"></i>
                  {{ ruleForm.hsTaskNum }}
                  <i @click="up(1)"
                    style="cursor: pointer;text-align: center;;line-height: 3rem;background-color: #f5f7fa;width: 3.5rem;"
                    class="el-icon-plus"></i>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8" style="margin-left: 11.5rem;">
              <el-form-item label="投料任务执行组数：" label-width="150px">
                <!-- <el-input-number v-model="ruleForm.tlTaskNum" @keydown.native="channelInputLimit" @change="handleChange"
                    :min="0"></el-input-number> -->
                <div
                  style="font-size: 1.2rem; border: 1px solid #e6e8eb;border-radius: 10px;width:16rem; display: flex;justify-content: space-between;">
                  <i @click="down(0)"
                    style="cursor: pointer;text-align: center;;line-height: 3rem;background-color: #f5f7fa;width: 3.5rem;"
                    class="el-icon-minus"></i>
                  {{ ruleForm.tlTaskNum }}
                  <i @click="up(0)"
                    style="cursor: pointer;text-align: center;;line-height: 3rem;background-color: #f5f7fa;width: 3.5rem;"
                    class="el-icon-plus"></i>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="margin-left: 10.8rem;">
          任务执行顺序：
          <draggable v-model="list" animation="1000" @start="onStart" @end="onEnd">
            <transition-group style="display: grid; grid-template-columns: repeat(9, 1fr) ;">
              <div style="margin-left: 2rem; width: 6rem;margin-top: 2rem;" class="item" v-for="(item, index) in list"
                :key="item.id">
                <span style="display: flex;">
                  <el-button>{{ item.value }} </el-button><i v-show="index != list.length - 1"
                    style="margin:0 2rem;line-height: 3rem;font-size: 2rem;font-weight: 100;" class="el-icon-right"></i>
                </span>

              </div>
            </transition-group>
          </draggable>
        </div>
        <div class="dialog-footer" style="display: flex;justify-content: space-between;">
          <div></div>
          <div>
            <el-button class="btn-light-blue" @click="submitForm('formName')">保存</el-button>
            <el-button if="!statusOpen" @click="watchpc">排程预览</el-button>
          </div>
        </div>
      </div>
      <!-- <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="增氧区域划分" name="first">
        </el-tab-pane>
        <el-tab-pane label="排污、换水区域划分" name="second">
          <pollution></pollution>
        </el-tab-pane>
        <el-tab-pane label="投料分组划分" name="third">
          <batchCharge></batchCharge>
        </el-tab-pane>
        <el-tab-pane label="任务配置" name="fourth">

        </el-tab-pane>
      </el-tabs> -->


    </div>
    <AddEditDialog :addEditId="addEditId" :addEditStatus="addEditStatus" :addEditIsDialog="addEditIsDialog">
    </AddEditDialog>
  </div>
</template>
<script>
import draggable from 'vuedraggable'
import NxTable from '@/components/NxTable.vue'
import AddEditDialog from './components/addEditDialog.vue'
import pollution from './components/pollution.vue'
import oxygenation from './components/oxygenation.vue'
import batchCharge from './components/batchCharge.vue'
import { Page } from '@/utils/pagination'
import {
  getConfigAutoTaskConfig,
  saveConfigAutoTaskConfig,
  getConfigAutoTaskConfigPreview
} from '@/api/system'
import { getCompanyInfoTree } from '@/api/company'
import mixin from '@/api/CompanyInfoTree.js'
export default {
  mixins: [mixin],
  components: {
    NxTable,
    AddEditDialog,
    pollution,
    batchCharge,
    draggable,
    oxygenation
  },
  // 表格数据
  data() {
    return {
      activeName: 'first',
      list: [],
      // 查询字段
      searchForm: {
        pageNum: 1,
        pageSize: 10,
        baseId: '',
        code: '',
        userType: '',
        companyId: '',
        deviceStatus: '',
        name: '',
        tailWaterModel: '',
        type: '',
      },
      ruleForm: {
        startTime: '',
        hsTaskNum: '',
        pwTaskNum: '',
        taskOrder: [],
        timeInterval: '',
        tlTaskNum: '',
        zyTaskNum: '',
      },
      statusOpen: true,
      rules: {
        // 表单规则

      },
      seeType: false,
      // 表格字段
      tableCols: [
        {
          label: '组名',
          prop: 'name',
          align: 'center',
          width: 120
        },
        {
          label: '控制箱',
          prop: 'name',
          align: 'center',
        },
        {
          label: '执行顺序',
          prop: 'createName',
          align: 'center',
        },

        {
          label: '操作',
          slot: 'operation',
          align: 'center',
          width: 180,
          fixed: 'right',
        },
      ],
      tableData: [],
      pagination: new Page(),
      crumbsStatus: '', // 三级面包屑名称
      typeDialog: false,
      addEditIsDialog: false, // 添加编辑页面状态
      addEditStatus: 'add',
      addEditId: '', // 添加编辑rowid
      baseArray: [], // 角色集合
      companyArray: [], // 公司集合
      userType: '', // 用户类型（0超级管理员，1公司管理员，2公司员工）
    }
  },
  // 初始化加载
  mounted() {
    this.userType = Number(window.localStorage.getItem('userType'))
    this.searchForm.userType = this.userType
    this.getCompanyInfoTree()
    this.activeName = this.$route.query.activeName ? this.$route.query.activeName : 'first'
    setTimeout(() => {
      this.getList()
    }, 1000);
  },
  // 自定义方法
  methods: {
    watchpc() {
      this.$router.push({
        path: `/schedule/SchedulePreview`,
        query: {
          id: this.ruleForm.id,
          baseId: this.searchForm.baseId,
          companyId: this.searchForm.companyId,
        },
      })
      // getConfigAutoTaskConfigPreview({ id: this.ruleForm.id }).then((res) => {
      //   if (res.code == 200) {
      //     let list = res.data.data
      //   }
      // });
    },
    down(id) {
      if (id == 0) {
        for (let i = 0; i < this.list.length; i++) {
          if (this.list[i].type == id && this.ruleForm.tlTaskNum != 0) {
            this.list.splice(i, 1)

            this.ruleForm.tlTaskNum--
            return
          }

        }
      } else if (id == 1) {
        for (let i = 0; i < this.list.length; i++) {
          if (this.list[i].type == id && this.ruleForm.hsTaskNum != 0) {
            this.list.splice(i, 1)
            this.ruleForm.hsTaskNum--
            return
          }
        }
      } else if (id == 2) {
        for (let i = 0; i < this.list.length; i++) {
          if (this.list[i].type == id && this.ruleForm.pwTaskNum != 0) {
            this.list.splice(i, 1)
            this.ruleForm.pwTaskNum--
            return
          }
        }
      } else if (id == 3) {
        for (let i = 0; i < this.list.length; i++) {
          if (this.list[i].type == id && this.ruleForm.zyTaskNum != 0) {
            this.list.splice(i, 1)
            this.ruleForm.zyTaskNum--
            return
          }

        }
      }
    },
    up(id) {
      if (id == 0) {
        let a = {}
        a.type = 0
        a.value = '投料'
        a.id = Math.floor(Math.random() * 100) + 1
        this.list.push(a)
        this.ruleForm.tlTaskNum++
      } else if (id == 1) {
        let a = {}
        a.type = 1
        a.value = '换水'
        a.id = Math.floor(Math.random() * 100) + 1
        this.list.push(a)
        this.ruleForm.hsTaskNum++
      } else if (id == 2) {
        let a = {}
        a.type = 2
        a.value = '排污'
        a.id = Math.floor(Math.random() * 100) + 1
        this.list.push(a)
        this.ruleForm.pwTaskNum++
      } else if (id == 3) {
        let a = {}
        a.type = 3
        a.value = '增氧'
        a.id = Math.floor(Math.random() * 100) + 1
        this.list.push(a)
        this.ruleForm.zyTaskNum++
      }
    },
    //开始拖拽事件
    onStart() {
      this.drag = true;
    },
    //拖拽结束事件
    onEnd() {
      this.drag = false;
    },
    // openStatus(row) {
    //   updateConfigFishpondModelStatus({ id: row.id }).then((res) => {
    //     if (res.code == 200) {
    //       this.$message({
    //         type: 'success',
    //         message: res.msg,
    //       })
    //     }
    //   })
    // },
    // 提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.ruleForm);
          let list = []
          this.list.map(item => {
            list.push(item.type)
          })
          this.ruleForm.taskOrder = list.join(',')
          saveConfigAutoTaskConfig(this.ruleForm).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: res.msg,
              });
              this.getList()
              this.statusOpen = false
            }
          });
        }
      });
    },
    handleDetail(row) {
      // console.log(row);
      // <span v-if="scope.row.type == 0">进水控制箱</span>
      //     <span v-if="scope.row.type == 1">鱼池控制箱</span>
      //     <span v-if="scope.row.type == 2">尾水控制箱</span>
      // let type = ''
      // if (row.type == 0) {
      //   type = '进水控制箱'
      // } if (row.type == 1) {
      //   type = '鱼池控制箱'
      // } if (row.type == 2) {
      //   type = '尾水控制箱'
      // }
      // console.log(row);
      console.log(row)
      this.$router.push({
        path:
          `/schedule/scheduledetails?baseId=` +
          row.baseId +
          '&id=' +
          row.id +
          '&companyId=' +
          row.companyId,
      })
    },
    // 查询
    onSubmit() {
      this.pagination.pageNum = 1
      this.getList()
    },
    // 分页查询
    refresh(val) {
      this.searchForm.pageNum = val.pageNum
      this.searchForm.pageSize = val.pageSize
      this.getList()
    },
    // 重置
    resetForm() {
      this.searchForm = {
        pageNum: 1,
        pageSize: 10,
        baseId: '',
        code: '',
        companyId: '',
        deviceStatus: '',
        name: '',
        tailWaterModel: '',
        type: '',
      }

      this.onSubmit()
    },
    // 查询列表
    getList() {
      getConfigAutoTaskConfig({ id: this.searchForm.baseId }).then((res) => {
        if (res.code == 200) {
          this.ruleForm = res.data
          this.ruleForm.taskOrder = this.ruleForm.taskOrder.split(',')
          let list = []
          for (let i = 0; i < this.ruleForm.taskOrder.length; i++) {
            if (this.ruleForm.taskOrder[i] == 0) {
              let a = {}
              a.type = 0
              a.value = '投料'
              a.id = i
              list.push(a)
            } else if (this.ruleForm.taskOrder[i] == 1) {
              let a = {}
              a.type = 1
              a.value = '换水'
              a.id = i
              list.push(a)
            } else if (this.ruleForm.taskOrder[i] == 2) {
              let a = {}
              a.type = 2
              a.value = '排污'
              a.id = i
              list.push(a)
            }
            else if (this.ruleForm.taskOrder[i] == 3) {
              let a = {}
              a.type = 3
              a.value = '增氧'
              a.id = i
              list.push(a)
            }
          }
          this.list = list
          console.log(this.ruleForm, list);

        }
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          delConfigAutoTaskGroup({ id: row.id }).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: res.msg,
              })
              this.getList()
            }
          })
        })
        .catch((err) => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 添加
    handleAdd() {
      this.addEditId = ''
      this.addEditStatus = 'add'
      this.addEditIsDialog = true
    },
    // 编辑
    handleEdit(row) {
      this.addEditId = row.id + ''
      this.addEditStatus = 'edit'
      this.addEditIsDialog = true
    },
    // 编辑添加取消关闭
    closeAddEdit() {
      this.addEditIsDialog = false
    },
    // 面包屑
    crumbsClick() {
      this.typeDialog = false
    },
    // 启用、禁用
    handleStatus(row) {
      openOrCloseSysUser({ id: row.id }).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: res.msg,
          })
          this.getList()
        }
      })
    },
    // 用户类型切换
    typeChange() {
      this.searchForm.companyId = ''
      this.companyArray = []

      this.searchForm.roleId = ''
      this.baseArray = []

      // 获取公司列表
      this.getCompanyInfoTree()

      // 查询
      this.onSubmit()
    },

    // 公司下拉切换
    changeTreeItem(val) {
      if (val) {
        this.searchForm.companyId = val[val.length - 1]
      } else {
        this.searchForm.companyId = ''
      }

      this.searchForm.baseId = ''
      this.baseArray = []

      this.getList()

      // 获取角色列表
      this.getSysCompanyBases()
    },
  },
}
</script>
<style lang="less" scoped>
.main-breadcrumb {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 76px;
  border-bottom: solid 20px #f2f2f2;
  padding-left: 20px;

  .main-breadcrumb-wrap {
    font-size: 16px;
    line-height: 68px;

    .main-breadcrumb-home {
      cursor: pointer;
      color: #666666;
      font-weight: bold;
    }

    .main-breadcrumb-sp {
      color: #666666;
      font-weight: bold;
    }
  }
}

.title {
  font-size: 20px;
  font-weight: bold;
  color: #166bb6;
  text-shadow: 2px 3px 1px rgb(226, 226, 226);
  margin-left: 1rem;
  margin-top: 2rem;
  margin-bottom: 2rem;
}
</style>
